package 代码随想录.链表;

import common.ListNode;

public class a24两两交换链表中的节点 {
    static class Solution {
        public ListNode swapPairs0(ListNode head) {
            ListNode solider = new ListNode();
            solider.next = head;
            ListNode cur = solider;
            ListNode next = cur.next;
            while (next != null && next.next != null) {
                ListNode newHead = next.next.next;
                cur.next = next.next;
                next.next.next = next;
                next.next = newHead;

                cur = next;
                next = cur.next;
            }
            return solider.next;
        }

        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode next = head.next;
            ListNode newHead = swapPairs(next.next);
            next.next = head;
            head.next = newHead;
            return next;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode read = ListNode.read(new Integer[]{1, 2, 3, 4});
        ListNode listNode = solution.swapPairs(read);
        ListNode.print(listNode);
    }
}
